﻿Imports System.Data.SqlServerCe

Namespace Data
    Public Class Connection
        Implements IDisposable

        Private Shared mNextConnectionId As Integer = 0
        Private Shared mNextConnectionSync As New Object
        Private Shared Function GetNextId() As Integer
            SyncLock mNextConnectionSync
                mNextConnectionId += 1
                If mNextConnectionId = Integer.MaxValue Then mNextConnectionId = 0
                Return mNextConnectionId
            End SyncLock
        End Function
        Private mConnection As SqlCeConnection
        Public ReadOnly Id As Integer
        Friend Sub New(ByVal connection As SqlCeConnection)
            Id = GetNextId()
            mConnection = connection
        End Sub
        Friend Function GetCEConnection() As SqlCeConnection
            Return mConnection
        End Function

        Public Sub Open()
            Environment.OnDBTraceInfoOpenConnection(Me)
            mConnection.Open()
        End Sub
        Public Sub Close()
            Environment.OnDBTraceInfoCloseConnection(Me)
            mConnection.Close()
        End Sub

        Private disposedValue As Boolean = False        ' To detect redundant calls

        ' IDisposable
        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
            If Not Me.disposedValue Then
                If disposing Then
                    ' TODO: free other state (managed objects).
                End If
                Close()

                ' TODO: free your own state (unmanaged objects).
                ' TODO: set large fields to null.
            End If
            Me.disposedValue = True
        End Sub

#Region " IDisposable Support "
        ' This code added by Visual Basic to correctly implement the disposable pattern.
        Public Sub Dispose() Implements IDisposable.Dispose
            ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
#End Region

    End Class
End Namespace